package com.huishen.edrivenew.ui;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.TextView;

import com.huishen.edrivenew.AppContext;
import com.huishen.edrivenew.Constants;
import com.huishen.edrivenew.R;
import com.huishen.edrivenew.adapter.AppointmentSubExListApdater;
import com.huishen.edrivenew.adapter.TimeClassApointListener;
import com.huishen.edrivenew.base.BaseActivity;
import com.huishen.edrivenew.bean.CoaLessonInfoBean;
import com.huishen.edrivenew.bean.CoachBean;
import com.huishen.edrivenew.bean.DateBean;
import com.huishen.edrivenew.bean.StudentBean;
import com.huishen.edrivenew.net.BitmapManager;
import com.huishen.edrivenew.net.JsonResponseHandler;
import com.huishen.edrivenew.net.NetApi;
import com.huishen.edrivenew.util.StringUtils;
import com.huishen.edrivenew.widget.CalendarUtil;
import com.huishen.edrivenew.widget.CircleImageView;
import com.huishen.edrivenew.widget.MassageListener;
import com.huishen.edrivenew.widget.MessageDialog;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * 旧模式预约学车页面
 */
public class RequestCoachActivity extends BaseActivity {
    

    @InjectView(R.id.header_title)
    public TextView title;
    @InjectView(R.id.header_back)
    public ImageButton back;

    @InjectView(R.id.appoint_expandablelist)
    public ExpandableListView list;
    @InjectView(R.id.f_appoint_photo)
    public CircleImageView coachHead;
    @InjectView(R.id.f_appoint_coachname)
    public TextView coachName;
    @InjectView(R.id.f_appoint_coachcar)
    public TextView coachCar;
    @InjectView(R.id.f_appoint_carnum)
    public TextView coachCarNumber;

    @InjectView(R.id.appoint_tv_time)
    public TextView time;
    @InjectView(R.id.appoint_tv_week)
    public TextView week;


    private DateBean currentDateBean;
    private CoachBean bean;

    private CoaLessonInfoBean lessonInfoBean;

    private AppointmentSubExListApdater adapter;

    private String[] sub = new String[] { "", "科目一", "科目二", "科目三", "科目四" };
    private String[] classtime = new String[] { "上午", "下午", "晚上" };

    private MessageDialog mdialog;
    BitmapManager bmpManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.activity_apointment);
        ButterKnife.inject(this);

        setDate();
        // 请求数据
        request();
    }


    private void setDate() {
        bean = AppContext.getInstance()._7DaysInfo.cohInfo;
        if(bean == null) {
            return;
        }
        coachName.setText(bean.name);
        coachCar.setText(bean.carBrand);
        coachCarNumber.setText(bean.carNum);
        
        if(!StringUtils.isEmpty(bean.path)) {
            bmpManager = new BitmapManager(BitmapFactory.decodeResource(AppContext.getInstance().getResources(), 
                R.drawable.photo_bg_t));
            bmpManager.loadBitmap(bean.path, coachHead);
        }

        if(AppContext.getInstance().dateBean != null) {
            currentDateBean = AppContext.getInstance().dateBean;
        }
        this.week.setText(CalendarUtil.getDayWeek(currentDateBean.getDateString()) + "");
        this.time.setText(currentDateBean.getDateStringZh());
    }
    
    

    
    
    private void request() {
        showDialog();
        NetApi.queryCohLessonInfoCount(this, new JsonResponseHandler() {
            @Override
            public void onSuccess(int code, JSONObject jsonObj, Object[] args) {
                try {
                    lessonInfoBean = (CoaLessonInfoBean) CoaLessonInfoBean.parseJson(jsonObj);
                    setListDate();

                } catch (Exception e) {
                    e.printStackTrace();
                    showToast("获取数据失败！");
                }
                dismissDialog();
            }

            @Override
            public void onFailure(int code, String errorMessage, Object[] args) {
                dismissDialog();
                showToast("获取数据失败！");
            }
            @Override
            public void onSessionFailure() {
                dismissDialog();
                super.onSessionFailure();
            }
        }, bean.id + "", currentDateBean.getDateString());
    }

    //设置listview
    private void setListDate() {
        adapter = new AppointmentSubExListApdater(this, lessonInfoBean,
                listener);
        list.setAdapter(adapter);
        if (adapter.getGroupCount() >= 0) {
            list.expandGroup(0);
            list.expandGroup(1);
        }
    }





    private TimeClassApointListener listener = new TimeClassApointListener() {

        @Override
        public void setOnClick(int subject, int timeType, int code) {
            if (code == 0) {
                actionAppoint(subject, timeType);
            } else {
                actionCancel(subject, timeType);
            }
        }

    };


    private void actionAppoint(final int subject, final int timeType) {
        // TODO 预约2 3 不能同时

        mdialog = new MessageDialog(this, "您确定要预约以下练习时间吗？", "练习项目：" + sub[subject]
                + "\n" + "练车时间：" + currentDateBean.getDateString() + " " + classtime[timeType - 1],
                false, new MassageListener() {
            @Override
            public void setCommitClick() {
                sendAppoint(subject, timeType);
            }
            @Override
            public void setCancelClick() {
            }
        });
        mdialog.show();
    }

    /**
     * 取消按钮响应
     */
    private void actionCancel(final int subject, final int timeType) {
        mdialog = new MessageDialog(this, "您确定取消预约的时间吗？", "", true,
                new MassageListener() {

                    @Override
                    public void setCommitClick() {
                        cancelAppoint(subject, timeType);
                    }
                    @Override
                    public void setCancelClick() {
                    }
                });
        mdialog.show();
    }


    private void sendAppoint(int subject, int timeType) {
        showDialog();
        
        NetApi.addLessonInfo(this, new JsonResponseHandler() {
            @Override
            public void onSuccess(int code, JSONObject jsonObj, Object[] args) {
                dismissDialog();
                try {
                    if (code == Constants.N_SUCCESS) {
                        showToast("预约成功！");
                        updateDate();
                    } else {
                        showToast("预约失败，请稍后再试！");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    showToast("预约失败，请稍后再试！");
                }
            }

            @Override
            public void onFailure(int code, String errorMessage, Object[] args) {
                dismissDialog();
                showToast("操作失败，请稍后再试！");
            }
            @Override
            public void onSessionFailure() {
                dismissDialog();
                super.onSessionFailure();
            }
        }, bean.id + "", currentDateBean.getDateString(), subject, timeType);
    }

    private void cancelAppoint(int subject, int timeType) {
        showDialog();
        NetApi.editLesssonInfoStatus(this, new JsonResponseHandler() {
            @Override
            public void onSuccess(int code, JSONObject jsonObj, Object[] args) {
                dismissDialog();
                try {
                    if (code == Constants.N_SUCCESS) {
                        showToast("取消成功！");
                        updateDate();
                    } else {
                        showToast("操作失败，请稍后再试！");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    showToast("操作失败，请稍后再试！");
                }
            }

            @Override
            public void onFailure(int code, String errorMessage, Object[] args) {
                dismissDialog();
                showToast("操作失败，请稍后再试！");
            }
            @Override
            public void onSessionFailure() {
                dismissDialog();
                super.onSessionFailure();
            }
        }, subject, timeType, currentDateBean.getDateString());
    }


    // TODO
    private void updateDate() {
        toMain();
    }

    @OnClick(R.id.header_back)
    public void toMain() {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        this.startActivity(intent);
        this.finish();
    }

}
